package cn.ctodb.commons.fdfs;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerGroup;
import org.csource.fastdfs.TrackerServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.ctodb.commons.pool.Object;

public class Client implements Object {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	private TrackerGroup tg;
	private String[] servers;
	private StorageServer ss;
	private TrackerServer ts;

	public Client(String[] servers) {
		this.servers = servers;
		try {
			init();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void init() throws IOException {
		ClientGlobal.setG_charset("UTF-8");
		InetSocketAddress[] inetSocketAddress = new InetSocketAddress[servers.length];
		for (int i = 0; i < servers.length; i++) {
			String[] ss = servers[i].split(":");
			inetSocketAddress[i] = new InetSocketAddress(ss[0], Integer.parseInt(ss[1]));
		}
		tg = new TrackerGroup(inetSocketAddress);
		TrackerClient tc = new TrackerClient(tg);

		ts = tc.getConnection();

		logger.info("[创建TrackerServer(createTrackerServer)]");
		try {
			ss = tc.getStoreStorage(ts);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("[创建TrackerServer(createTrackerServer)][异常：{}]", e);
		}
		ts.close();
	}

	public String upload(byte[] bytes, String extName) throws IOException {
		try {
			StorageClient1 sc1 = new StorageClient1(ts, ss);
			NameValuePair[] meta_list = null;
			String fileid = sc1.upload_file1(bytes, extName, meta_list);
			logger.info("Upload local file " + "" + " ok, fileid=" + fileid);
			return fileid;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}

	/**
	 * 删除文件（注意tracker对应的nginx下的缓存）
	 * 
	 * @param fileId
	 *            上传时候返回的路径即为唯一标示
	 * @return 删除是否成功标志
	 */
	public void delete(String fileId) throws IOException {
		try {
			StorageClient1 storageClient = new StorageClient1(ts, ss);
			storageClient.delete_file1(fileId);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
	}

	public byte[] load(String fileid) throws IOException, MyException {
		StorageClient1 storageClient = new StorageClient1(ts, ss);
		return storageClient.download_file1(fileid);
	}

	@Override
	public void destroy() {
		try {
			ss.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			ts.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
